import type { ProFormInstance } from '@ant-design/pro-components';
import style from './createpaper.module.scss'
import {ProCard,ProFormSelect,ProFormText,ProFormTextArea,StepsForm,ProFormRadio,ModalForm,} from '@ant-design/pro-components';
import { Divider, Table,TableColumnsType, TableProps,Card, message,Input,  Button, Space,Form  } from 'antd';
import { useEffect, useMemo, useRef,useState } from 'react';
import {getsubjects,getaddcreate} from '../../../services/index'
import type {subjectslist,SelectquestionType,addcreateType } from '../../../services/type'
// 点击科目后调取题目的接口
import {QuestionDataApi} from '../../../service/index'
import { useNavigate } from 'react-router-dom';
//第二步组件
import StepTwo from './Steptwo/StepTwo';

// 创建试卷信息类型
export interface PaperInformation {
  name?: string;
  classify?: string;
  way?: string;
  remark?: string;
  children?: SelectquestionType[];
}

export interface DataType {
  key: string;
  question: string;
  type: string;
  answer: string;
}
 
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];

const CreatePaper = () => {
  const navigate = useNavigate()
  const formRef = useRef<ProFormInstance | null>(null);
  // 所有科目
  const [allsubjects,setAllsubjects] = useState<subjectslist[]> ([])
  const [newlist,setNewlist] = useState<string[]> ([])
  // 存储点击科目后拿到的数据
  const  [subjectsdate,setSubjectsdate] = useState<SelectquestionType []> ([])
  // 存储创建的试卷的信息
  const [paperinformation,setPaperinformation] = useState<PaperInformation | null> (null)
  // 点击提交时传入的参数
  const [querys,setQuerys] = useState<addcreateType  | null> (null)
  // 存储随机组件时传入的随机数
  const [total,setTotal] = useState(0)
  // 获取随机数据
  const randomlist = useMemo(()=>{
    console.log(total)
    const arr=[]
    while(arr.length<total){
      arr.push(subjectsdate[Math.floor(Math.random()*(total-1-0+1)+0)])
    }
    console.log(arr)
    return arr
  },[total])


  const [form] = Form.useForm<{ name: string; company: string }>();

  // const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');


  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 步骤表单自带数据
  const [selectedRows, setSelectedRows] = useState<DataType[]>([]);
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[], newSelectedRows: DataType[]) => {
      console.log('selectedRowKeys changed: ', newSelectedRowKeys);
      console.log('selectedRows changed: ', newSelectedRows);
      setSelectedRowKeys(newSelectedRowKeys);
      setSelectedRows(newSelectedRows);
    },
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };


  const columns: TableColumnsType<DataType> = [
    {
      title: '题干',
      dataIndex: 'question',
      key: 'question',
    },
    {
      title: '题型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '答案',
      dataIndex: 'answer',
      key: 'answer',
    },
  ];
  // 渲染表格时的行数剧
  const dataSource = subjectsdate.map((item) => ({
    key:item._id,
    question: item.question,
    type: item.type,
    answer:item.answer,
  }));

  
  
  const getsubjectslist = async () => {
    const res = await getsubjects()
    console.log(res.data.data.list)
    setAllsubjects(res.data.data.list)
  }

  
  // 科目发生变化发生的函数
  const getQuestionData = async(vel:string) => {
    const res = await QuestionDataApi({
      classify:vel
    })
    console.log(res.data.data.list)
    setSubjectsdate(res.data.data.list)
  }

  const cahngediscipline = (vel:string) => {
    getQuestionData(vel)
  }

  useEffect(()=>{
    getsubjectslist()
  },[])

  const getobj = useMemo (()=>{
    let arr= []
    const newobj = allsubjects.map((vel,i)=>{
      return arr[i] = vel.name
    })
    setNewlist(newobj)
  },[allsubjects])


  const Components = {
    选题组卷:"选题组卷",
    随机组卷:"随机组卷",
  };
  const [type, setType] = useState<keyof typeof Components>('选题组卷')

  return (
    <div>
      <h2 style={{lineHeight:'60px'}}>创建试卷</h2>
      <ProCard className={style.bottom}>
        <StepsForm<{
          name: string;
        }>
          formRef={formRef}
          onFinish={async () => {
            getaddcreate(querys!)
            await waitTime(1000);
            message.success('Submission successful');
            navigate('/paper/paper-bank')
          }}
          formProps={{
            validateMessages: {
              required: '请输入试卷名称',
            },
          }}
        >
          <StepsForm.StepForm<{
            name: string;
          }>
            name="base"
            title="试卷基础信息"
            onFinish={async () => {
              console.log(formRef.current?.getFieldsValue());
              setPaperinformation({...paperinformation,name:formRef.current?.getFieldsValue().name,remark: formRef.current?.getFieldsValue().remark});
              setQuerys({...querys!,name:formRef.current?.getFieldsValue().name})
              await waitTime(2000);
              return true;
            }}
          >
            <ProFormText
              name="name"
              label="试卷名称"
              width="md"
              // tooltip="Up to 24 characters, used as a unique id"
              placeholder="请输入试卷名称"
              rules={[{ required: true }]}
            />
            <ProFormTextArea
              name="remark"
              label="备注"
              width="lg"
              placeholder="请输入备注"
            />
          </StepsForm.StepForm>
          <StepTwo formRef={formRef} setPaperinformation={setPaperinformation} paperinformation={paperinformation} newlist={newlist}
          cahngediscipline={cahngediscipline} querys={querys} setQuerys={setQuerys} type={type} setType={setType} selectedRows={selectedRows}
          setSelectedRows={setSelectedRows} selectedRowKeys={selectedRowKeys} setSelectedRowKeys={setSelectedRowKeys} waitTime={waitTime}
          rowSelection={rowSelection} columns={columns} dataSource={dataSource} total={total} setTotal={setTotal} randomlist={randomlist}
          />
          <StepsForm.StepForm
            name="time"
            title="展示试卷基本信息"
            className={style.Stepthree}
          >
            <h2>试卷信息</h2>
            <div><em>组卷名称：{paperinformation?.name}</em><em>科目：{paperinformation?.classify}</em><em>组卷方式：{paperinformation?.way ? paperinformation.way : '选题组卷'}</em></div>
            <p>备注：{paperinformation?.remark}</p>
            <Divider ><em>试题展示</em></Divider>
            {paperinformation?.children?.length ? (
              <Card title="试卷预览" style={{ width: '100%' }}>
                {paperinformation.children.map((item, index) => (
                  <div key={Math.random()} style={{ marginBottom: 16 }}>
                    <p><strong>题目 {index + 1}:</strong> {item.question}</p>
                    <p><strong>题型:</strong> {item.type}</p>
                    <p><strong>答案:</strong> {item.answer}</p>
                    <Divider />
                  </div>
                ))}
              </Card>
            ) : (
              <p>尚未选择题目</p>
            )}
          </StepsForm.StepForm>
        </StepsForm>
      </ProCard>
    </div>
    
  )
}

export default CreatePaper 